<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left">
          <Breadcrumb />
        </div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <StatusColum :status-name="scope.row.statusName" />
            </template>
          </el-table-column>
          <Column
            v-for="(column,index) in tableColumns"
            :key="index"
            :prop="column.prop"
            :is-show="column.isShow"
            :label="column.label"
            :sortable="column.sortable"
            :width="column.width"
            :align="column.align"
            :min-width="column.minWidth"
          />
          <el-table-column label="操作" align="center" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status ==0 || scope.row.status ==4 || scope.row.status ==5"
                v-hasPermi="['sale:deliver:edit']"
                type="text"
                @click.stop="edit(scope.row)"
              >编辑</el-button>
              <span v-else class="el-button--text button_grey">编辑</span>
              <el-button
                v-if="scope.row.status ==0 || scope.row.status ==4 || scope.row.status ==5"
                v-hasPermi="['sale:deliver:delete']"
                type="text"
                @click.stop="deleteOne(scope.row)"
              >删除</el-button>
              <span v-else class="el-button--text button_grey">删除</span>
              <el-button v-if="scope.row.status ==1" type="text" @click.stop="cancel(scope.row)">撤销</el-button>
              <!-- <el-button
                v-if="scope.row.status ==1"
                type="text"
                @click.stop="cancel(scope.row)"
              >撤销</el-button>-->
              <span v-else class="el-button--text button_grey">撤销</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>
    <!-- <el-dialog
      title="警告"
      :visible.sync="dialogWarn"
      width="450px"
    >
      <div class="titleText1">
        <svg-icon icon-class="不足" class="textContent_remak_svg" />
        <span class="textContent_remak">该单据已被锁定，不可撤销！</span>
      </div>
      <div class="textContent_remak2">需等待出库单提交审批结果。</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogWarn=false">确认</el-button>
      </span>
    </el-dialog>-->

    <el-dialog title="撤销确认" :visible.sync="dialogRevoke" width="450px">
      <div class="titleText1">
        <svg-icon icon-class="不足" class="textContent_remak_svg" />
        <span class="textContent_remak">是否确认撤销该单据？</span>
      </div>
      <div class="textContent_remak2">关联的出库单也将删除。</div>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="dialogRevoke=false">取消</el-button>
        <el-button type="primary" @click="cancelRevoke">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { getPageSettings } from '@/api/common/common'

import {
  list,
  remove,
  getInfo,
  repealDeliver
} from '@/api/saleManage/saleSend'
import { list as getEquipmentList } from '@/api/equipmentManage/baseInfo/equipmentInfo'
import { getInfo as showDetailSaleInfo } from '@/api/saleManage/saleOrder'
import StatusColum from './StatusColum.vue'
import { getDictSelects } from '@/api/common/common'
import AddOrUpdate from './addOrUpdate' // 新增或编辑页面
import ShowDetail from './showDetail.vue' // 查看页面
import showDetailSale from '../saleOrder/showDetail'
import { listForSale } from '@/api/saleManage/customerInfo'
import { mapGetters } from 'vuex'
export default {
  name: 'Index',
  components: { StatusColum },
  data() {
    return {
      loading: true,
      dialogWarn: false,
      dialogRevoke: false,
      tableRemokeColum: {}, // 撤销选中行数据
      isTableColumShow: true, // 表格状态列跟随页面配置隐藏显示
      pageId: '销售发货单', // 页面唯一标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      // tableKey: 1,
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [
        // 表格常规字段（初始值）
        // { prop: 'statusName', label: '状态', canOrder: false },
        {
          prop: 'code',
          label: '发货单号',
          sortable: 'custom',
          minWidth: '120'
        },
        {
          prop: 'customerName',
          label: '客户名称',
          canOrder: false,
          minWidth: '120'
        },
        {
          prop: 'deliverName',
          label: '制单人员',
          canOrder: false,
          minWidth: '120'
        },
        {
          prop: 'deliverTime',
          label: '制单日期',
          minWidth: '120',
          sortable: 'custom'
        },
        // { prop: 'saleOrderCode', label: '销售订单号' },
        {
          prop: 'freightByLabel',
          label: '运费承担方',
          minWidth: '120',
          canOrder: false
        },
        { prop: 'remark', label: '备注', canOrder: false, minWidth: '160' },
        {
          prop: 'cost',
          label: '费用',
          minWidth: this.SETTINGS.settings_decimalDigits_length,
          canOrder: false,
          align: 'right'
        }
      ],
      defaultSearchColumns: [
        // 搜索区常规字段（初始值）
        { prop: 'code', label: '发货单号', type: 'input' },
        {
          prop: 'customerId',
          label: '客户名称',
          type: 'select',
          optionsName: 'customerNamesddData'
        },
        { prop: 'deliverTime', label: '制单日期', type: 'time' },
        {
          prop: 'statusList',
          label: '状态',
          type: 'select-multiple',
          optionsName: 'statusOptions'
        },
        { prop: 'deliverName', label: '制单人员', type: 'input' },
        {
          prop: 'freightBy',
          label: '运费承担方',
          type: 'select',
          optionsName: 'freightByOptions'
        }
      ],
      freightByOptions: [],
      customerNamesddData: [],
      operationData: [
        // 右上角的操作按钮
        { label: '新增', perm: 'sale:deliver:add' },
        { label: '批量删除', perm: 'sale:deliver:delete' },
        { label: '打印', perm: 'sale:deliver:list' },
        { label: '页面配置', perm: '' }
      ],
      statusOptions: [
        // 选择组件数据源
        // { value: undefined, label: '全部' },
        { value: '0', label: '草稿' },
        { value: '1', label: '待发货' },
        { value: '2', label: '已发货' },
        { value: '3', label: '审批中' },
        { value: '4', label: '已驳回' },
        { value: '5', label: '已撤销' }
      ],
      showKey: [
        {
          name: '基本信息',
          columns: [
            { type: 'form', name: '发货单号', key: 'code' },
            { type: 'form', name: '制单人员', key: 'deliverName' },
            { type: 'form', name: '制单日期', key: 'deliverTime' },
            // { type: 'form', name: '销售订单号', key: 'saleOrderCode' },
            { type: 'form', name: '客户名称', key: 'customerName' },
            { type: 'form', name: '交货方式', key: 'deliveryTypeLabel' },
            { type: 'form', name: '收货人', key: 'customerName' },
            { type: 'form', name: '运费承担方', key: 'freightByLabel' },
            { type: 'form', name: '费用', key: 'cost' },
            {
              type: 'file',
              name: '附件',
              fileName: 'fileName',
              fileRealName: 'fileRealName',
              fileUrl: 'url'
            },
            { type: 'form', name: '备注', key: 'remark', length: 'double' },
            {
              type: 'table',
              name: '',
              key: 'data'
            }
          ]
        },
        {
          name: '客户信息',
          columns: [
            { type: 'formData2', name: '交货方式', key: 'deliveryTypeLabel' },
            { type: 'formData2', name: '联系人', key: 'consignee' },
            { type: 'formData2', name: '联系方式', key: 'phone' },
            { type: 'formData2', name: '注意事项', key: 'attentionMatters' },
            {
              type: 'formData2',
              name: '收货地址',
              key: 'deliveryAddress',
              length: 'double'
            }
          ]
        },
        {
          name: '审批详情',
          columns: [{ type: 'review', name: '评审进度', key: 'taskList' }]
        }
      ],
      showKey2: [
        {
          name: '基本信息',
          columns: [
            // { type: 'form', name: '销售订单号', key: 'code' },
            { type: 'form', name: '制单人员', key: 'orderName' },
            { type: 'form', name: '制单日期', key: 'orderTime' },
            { type: 'form', name: '订单类型', key: 'orderTypeLabel' },
            { type: 'form', name: '客户名称', key: 'customerName' },
            { type: 'form', name: '订货日期', key: 'orderGoodsTime' },
            { type: 'form', name: '合同号', key: 'contractCode' },
            { type: 'form', name: '未税总金额', key: 'allPrice' },
            { type: 'form', name: '含税总金额', key: 'taxAllPrice' },
            { type: 'form', name: '税额', key: 'tax' },
            {
              type: 'file',
              name: '附件',
              fileName: 'fileName',
              fileRealName: 'fileRealName',
              fileUrl: 'url'
            },
            { type: 'form', name: '备注', key: 'remark', length: 'double' },
            {
              type: 'table',
              name: '',
              key: 'data'
            }
          ]
        },
        {
          name: '客户信息',
          columns: [
            { type: 'formData', name: '计税方式', key: 'taxTypeLabel' },
            { type: 'formData', name: '税率%', key: 'taxRateLabel' },
            { type: 'formData', name: '结算方式', key: 'settlementTypeLabel' },
            {
              type: 'formData',
              name: '结算币别',
              key: 'settlementCurrencyLabel'
            },
            { type: 'formData2', name: '交货方式', key: 'deliveryTypeLabel' },
            { type: 'formData2', name: '联系人', key: 'consignee' },
            { type: 'formData2', name: '联系方式', key: 'phone' },
            { type: 'formData2', name: '注意事项', key: 'attentionMatters' },
            {
              type: 'formData2',
              name: '收货地址',
              key: 'deliveryAddress',
              length: 'double'
            }
          ]
        },
        {
          name: '审批详情',
          columns: [{ type: 'review', name: '评审进度', key: 'taskList' }]
        }
      ]
    }
  },
  watch: {
    notificationId(newValue, oldValue) {
      if (
        newValue !== oldValue &&
        newValue !== 0 &&
        this.$store.state.notification.notificationStatus == '1'
      ) {
        const rowId = { id: this.notificationId }
        this.showDetail(rowId)
      }
    }
  },
  created() {
    // this.loadEquipmentList();
    this.getDictOptions()
    if (this.notificationId !== 0) {
      const rowId = { id: this.notificationId }
      if (this.$store.state.notification.notificationStatus == '1') {
        this.showDetail(rowId)
      }
    }
    this.getCustomerNamesdd()
    if (this.$store.state.order.contendId) {
      this.showDetail({ id: this.$store.state.order.contendId })
      this.$store.state.order.contendId = ''
    }
    this.getPageSettings()
  },
  computed: {
    ...mapGetters(['notificationId'])
  },
  mounted() {},
  methods: {
    cellStyle({ row, column }) {
      if (column.property == 'code') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
      if (column.property == 'saleOrderCode') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'code':
          this.showDetail(row)
          break
        case 'saleOrderCode':
          this.showDetailSale(row)
          break
      }
    },
    // 获取页面配置显示状态
    // getPageSettings() {
    //   getPageSettings({ userId: this.userId, pageId: this.pageId }).then(res => {
    //     if (res.data.json) {
    //       const data = res.data.json.TableColumns
    //       data.map((item) => {
    //         if (item.label == '状态') {
    //           this.isTableColumShow = item.isShow
    //         }
    //       })
    //     } else {
    //       return
    //     }
    //   })
    // },
    showDetailSale(row) {
      showDetailSaleInfo(row.saleOrderId).then(res => {
        res.data.status = 3
        this.$layer.iframe({
          // 弹框
          content: {
            content: showDetailSale, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: res.data,
              showKey: this.showKey2
            } // props
          },
          area: ['1320px', '700px'],
          title: '查看销售订单号', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
    },
    showDetail(row) {
      getInfo(row[this.mainId]).then(res => {
        if (res.data.status != 0 && res.data.isApprovalShow != 1) {
          const obj = {
            taskNoName: '审批结束',
            taskList: []
          }
          if (
            res.data.taskList[res.data.taskList.length - 1].approvalStatus ==
              3 ||
            res.data.taskList[res.data.taskList.length - 1].approvalStatus == 4
          ) {
            obj.approvalStatus = 5
          } else {
            obj.approvalStatus = 0
          }
          res.data.taskList.push(obj)
        } // 跳转过来直接查看审批
        this.$layer.iframe({
          // 弹框
          content: {
            content: ShowDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: {
                ...res.data,
                customerName: res.data.saleCustomerListVo.name,
                deliveryTypeLabel:
                  res.data.saleDeliverInformation ? res.data.saleDeliverInformation.deliveryTypeLabel : ''
              },
              showKey: this.showKey,
              businessId: row[this.mainId]
            } // props
          },
          area: ['1350px', '700px'],
          title: '查看销售发货单', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
      this.$store.dispatch('notification/changeId', 0)
    },
    getCustomerNamesdd() {
      listForSale(this.pageData).then(res => {
        const cacheData = []
        res.data.forEach(item => {
          cacheData.push({
            value: item.id,
            label: item.name
          })
        })
        this.customerNamesddData = cacheData
        // this.tableData = res.data
        // this.total = res.total
        // this.loading = false
        // this.$nextTick(() => {
        //   this.setSelectRow(this)// 设置行选中
        //   this.tableHeight = this.$refs.table_container.offsetHeight
        // })
      })
    },
    getDictOptions() {
      getDictSelects('freightBy').then(res => {
        res.data.forEach(ele => {
          ele['label'] = ele.dictLabel
          ele['value'] = ele.dictCode
        })
        this.freightByOptions = res.data
      })
    },
    getExportData(data) {
      return list(data)
    },
    refresh() {
      this.pageData.pageNum = 1
      this.getList()
    },
    refresh2() {
      this.tableData = []
      setTimeout(() => {
        this.getList()
      }, 50)
    },
    getList() {
      list(this.pageData).then(res => {
        this.tableData = res.data
        this.total = res.total
        this.loading = false
        this.tableData.forEach(item => {
          if (item.status == 0 || item.status == 4 || item.status == 5) {
            item.canNotSelectDelete = false
          } else {
            item.canNotSelectDelete = true
          }
        })
        this.$nextTick(() => {
          this.setSelectRow(this) // 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
        })
      })
    },
    loadEquipmentList() {
      getEquipmentList({ status: 1 }).then(res => {
        res.data.forEach(item => {
          item['value'] = item.id
          item['label'] = item.deviceName
        })
        this.equipmentList = res.data
      })
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {} // props
        },
        area: ['1320px', '700px'],
        title: '新增销售发货单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    edit(row) {
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          } // props
        },
        area: ['1320px', '700px'],
        title: '编辑销售发货单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // cancel(row) {
    //   console.log(111)
    //   const _this = this
    //   this.$confirm('是否确定撤销该订单？', '撤销确认', {
    //     confirmButtonText: '确定撤销',
    //     cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
    //     type: 'warning'
    //   }).then(function() {
    //     repealDeliver(row[_this.mainId]).then(res => {
    //       _this.$message({
    //         message: res.msg,
    //         type: 'success'
    //       })
    //       _this.selectionsAll = []
    //       _this.getList()
    //     })
    //   }).catch(() => {})
    // },

    // 撤销弹框
    cancel(row) {
      this.tableRemokeColum = row
      const confirmText = ['是否确认撤销该单据？']
      const confirmText2 = ['关联的出库单也将删除。']
      const newDatas = []
      const h = this.$createElement
      newDatas.push(h('i', { class: 'el-icon-warning', style: 'color:#ffba00;font-size:24px;margin-right:12px;vertical-align: -4px' }))
      for (const i in confirmText) {
        newDatas.push(h('span', null, confirmText[i]))
      }
      for (const i in confirmText2) {
        newDatas.push(h('p', { style: 'color: rgba(74, 70, 70, 0.4);margin-left:36px' }, confirmText2[i]))
      }
      this.$confirm('撤销确认', {
        title: '撤销确认',
        message: h('div', null, newDatas),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'cancelConfirm'
      })
        .then(() => {
          const _this = this
          repealDeliver(_this.tableRemokeColum.id).then(res => {
            _this.$message({
              message: res.msg,
              type: 'success'
            })
            _this.selectionsAll = []
            _this.dialogRevoke = false
            _this.getList()
            _this.tableRemokeColum = {}
          })
          // 点击“确定”按钮后执行的方法
        })
        .catch(() => {
          this.dialogRevoke = false
          // 点击“关闭”按钮后执行的方法
        })
      // this.dialogRevoke = true;
    },
    // 撤销确认
    cancelRevoke() {
      console.log(111)
      const _this = this
      repealDeliver(_this.tableRemokeColum.id).then(res => {
        _this.$message({
          message: res.msg,
          type: 'success'
        })
        _this.selectionsAll = []
        _this.dialogRevoke = false
        _this.getList()
        _this.tableRemokeColum = {}
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      })
        .then(function() {
          remove(row[_this.mainId]).then(res => {
            _this.$message({
              message: res.msg,
              type: 'success'
            })
            _this.selectionsAll = []
            _this.getList()
          })
        })
        .catch(() => {})
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove(deleteIds)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-table__row {
  height: 44px;
}
.el-icon-warning-outline {
  font-size: 26px;
  color: rgb(255, 153, 0);
}
.titleText1 {
  margin: 15px 0 0 40px;
  color: #000000;
  font-size: 18px;
  height: 26px;
  .textContent_remak{
    font-size: 14px;
  }
}
.textContent_remak_svg {
  color: #ffba00;
  font-size: 24px;
  margin-right: 10px;
}
.textContent_remak2 {
  font-size: 14px;
  margin-left: 78px;
  margin-top: 5px;
  color: rgba(74, 70, 70, 0.4);
}
/deep/.el-dialog {
  text-align: left !important;
  height: 200px !important;
  margin-top: 40vh !important;
  border-radius: 8px;
  .el-dialog__body {
    height: auto;
    padding: 0 0 25px 0 !important;
    border-bottom: 1px solid rgba(242, 242, 242);
  }
  // .el-dialog__title{
  //   color: #000000 !important;
  // }
}
/deep/.el-dialog__header {
  //  background-color: rgb(32,126,249) !important;
  // padding-top: 15px;
  .el-dialog__title,
  .el-dialog__headerbtn,
  .el-dialog__close {
    font-size: 18px;
    //  color: #fff !important;
  }
}
</style>

